function switchTab(tab) {
    document.getElementById('tabRecent').classList.remove('tab-active');
    document.getElementById('tabAll').classList.remove('tab-active');
    document.getElementById('tabContentRecent').style.display = 'none';
    document.getElementById('tabContentAll').style.display = 'none';
    if (tab === 'recent') {
        document.getElementById('tabRecent').classList.add('tab-active');
        document.getElementById('tabContentRecent').style.display = '';
    } else {
        document.getElementById('tabAll').classList.add('tab-active');
        document.getElementById('tabContentAll').style.display = '';
    }
}
function renderRecentFileList(files) {
    const cardList = document.getElementById('recentFileCardList');
    cardList.innerHTML = files.map(file => `
        <div class="file-card">
            <div class="file-card-main">
                <div class="file-card-info">
                    <div class="file-card-header">
                        ${file.iconUrl ? `<img src="${file.iconUrl}" class="file-icon" alt="图标">` : ''}
                        <div style="display:flex;flex-direction: column;">
                            <span class="file-card-title">${file.name}</span>
                            ${file.appName ? `<small style=\"color:#888;display:block;margin-top:2px;\">${file.appName}</small>` : ''}
                        </div>
                    </div>
                    <div class="file-card-meta">
                        <span>更新时间: ${file.buildUpdated || ''}</span>
                        <span>大小: ${formatFileSize(file.size)} 字节</span>
                        ${file.version ? `<span>版本号: ${file.version}</span>` : ''}
                    </div>
                </div>
            </div>
            <div class="file-card-actions">
                <a href="${file.buildShortcutUrl}" target="_blank">下载</a>
                ${file.buildQRCodeURL ? `<a href="javascript:;" class="qr-link" data-qr="${file.buildQRCodeURL}">二维码</a>` : ''}
            </div>
        </div>
    `).join('');
}
function loadRecentFileList() {
    fetch('/api/recent-files')
        .then(response => response.json())
        .then(data => {
            renderRecentFileList(data.list || []);
        });
}
function formatFileSize(sizeInByte) {
    const bytes = sizeInByte;
    const units = ['Bytes', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;
    while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
    }
    return `${size.toFixed(2)} ${units[unitIndex]}`;
}
let allFiles = [];
let currentPage = 1;
let pageSize = 30;
let totalFiles = 0;

function renderPagination(total, page, pageSize) {
    const pageCount = Math.ceil(total / pageSize);
    let html = '';
    if (pageCount <= 1) return '';
    html += `<button class="pagination-btn" onclick="gotoPage(${page - 1})" ${page === 1 ? 'disabled' : ''}>上一页</button>`;
    html += ` <span class="pagination-info">第 ${page} / ${pageCount} 页</span> `;
    html += `<button class="pagination-btn" onclick="gotoPage(${page + 1})" ${page === pageCount ? 'disabled' : ''}>下一页</button>`;
    return `<div class="pagination-bar">${html}</div>`;
}
function gotoPage(page) {
    if (page < 1) return;
    const pageCount = Math.ceil(totalFiles / pageSize);
    if (page > pageCount) return;
    currentPage = page;
    loadFileList();
}


function renderFileList(files) {
    const cardList = document.getElementById('fileCardList');
    if (files.length === 0) {
        cardList.innerHTML = '<div class="no-results">没有找到匹配的文件，请尝试其他搜索关键词</div>';
    } else {
        cardList.innerHTML = files.map(file => `
            <div class="file-card">
                <div class="file-card-main">
                    <div class="file-card-info">
                        <div class="file-card-header">
                            ${file.iconUrl ? `<img src="${file.iconUrl}" class="file-icon" alt="图标">` : ''}
                            <div style="display:flex;flex-direction: column;">
                                <span class="file-card-title">${file.name}</span>
                                ${file.appName ? `<small style=\"color:#888;display:block;margin-top:2px;\">${file.appName}</small>` : ''}
                            </div>
                        </div>
                        <div class="file-card-meta">
                            <span>更新时间: ${file.buildUpdated || ''}</span>
                            ${`<span>大小: ${formatFileSize(file.size)} 字节</span>`}
                            ${file.version ? `<span>版本号: ${file.version}</span>` : ''}
                        </div>
                    </div>
                </div>
                <div class="file-card-actions">
                    ${file.isDirectory ? '' : `<a href="${file.buildShortcutUrl}" target="_blank">下载</a>`}
                    ${file.buildQRCodeURL ? `<a href="javascript:;" class="qr-link" data-qr="${file.buildQRCodeURL}">二维码</a>` : ''}
                </div>
            </div>
        `).join('');
    }
}
function loadFileList(searchTerm = '') {
    let url = `/api/files?page=${currentPage}&pageSize=${pageSize}`;
    if (searchTerm) {
        url += `&search=${encodeURIComponent(searchTerm)}`;
    }
    fetch(url)
        .then(response => response.json())
        .then(data => {
            totalFiles = data.total;
            renderFileList(data.list);
            document.getElementById('pagination').innerHTML = renderPagination(data.total, data.page, data.pageSize);
        });
}

function handleSearch() {
    const searchInput = document.getElementById('fileSearchInput');
    currentPage = 1;
    loadFileList(searchInput.value);
}


function uploader(form, input, callback) {
    form.addEventListener('submit', function (e) {
        e.preventDefault();

        callback.beforeUpload();

        // 如果没有选择文件，直接返回
        if (!input.files.length) {
            callback.afterUpload('请选择文件');
            return;
        }

        const formData = new FormData(this);
        fetch('/upload', {
            method: 'POST',
            body: formData,
            redirect: 'follow'
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    callback.afterUpload(null);
                    form.reset();
                } else {
                    callback.afterUpload('上传失败: ' + data.message);
                }
            })
            .catch(error => {
                callback.afterUpload('上传出错: ' + error);
            });
    });
}

// 添加二维码相关函数
function showQRCode(url) {
    const modal = document.getElementById('qrModal');
    const qrImage = document.getElementById('qrImage');
    qrImage.src = url;
    modal.style.display = 'block';
}
function closeQRModal() {
    const modal = document.getElementById('qrModal');
    modal.style.display = 'none';
}

// 拖拽上传逻辑
const dragDropArea = document.getElementById('dragDropArea');
const dragDropHint = document.getElementById('dragDropHint');
const statusDiv = document.getElementById('uploadStatus');
const fileInput = document.getElementById('file');
dragDropArea.addEventListener('dragover', function (e) {
    e.preventDefault();
    dragDropArea.style.background = '#eaf3ff';
});
dragDropArea.addEventListener('dragleave', function (e) {
    e.preventDefault();
    dragDropArea.style.background = '#f4f8ff';
});
dragDropArea.addEventListener('drop', function (e) {
    e.preventDefault();
    dragDropArea.style.background = '#f4f8ff';
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
        fileInput.files = e.dataTransfer.files;
        dragDropHint.textContent = '已选择文件：' + Array.from(e.dataTransfer.files).map(f => f.name).join(', ');
    }
});
dragDropArea.addEventListener('click', function () {
    fileInput.click();
});
fileInput.addEventListener('change', function () {
    if (fileInput.files && fileInput.files.length > 0) {
        dragDropHint.textContent = '已选择文件：' + Array.from(fileInput.files).map(f => f.name).join(', ');
    } else {
        dragDropHint.textContent = '拖拽文件到此处上传，或点击下方选择文件';
    }
});

// 在文件列表容器上绑定点击事件（事件委托）
Array.from(document.querySelectorAll('#fileListContainer, #recentFileCardList')).map((div) => {
    div.addEventListener('click', function (e) {
        // 处理二维码点击
        if (e.target.classList.contains('qr-link') || e.target.closest('.qr-link')) {
            e.preventDefault();
            const qrLink = e.target.classList.contains('qr-link') ? e.target : e.target.closest('.qr-link');
            showQRCode(qrLink.getAttribute('data-qr'));
        }
        // 处理下载点击
        else if (e.target.tagName === 'A' && e.target.closest('.file-card-actions') && e.target.getAttribute('target') === '_blank') {
            e.preventDefault();
            window.open(e.target.getAttribute('href'), '_blank');
        }
    });
});
// 点击模态框背景关闭
document.getElementById('qrModal').addEventListener('click', function (e) {
    if (e.target === this) {
        closeQRModal();
    }
});

uploader(document.getElementById('uploadForm'), fileInput, {
    beforeUpload: () => {
        statusDiv.textContent = '正在上传...';
    },
    afterUpload: (err, res) => {
        if (err) {
            statusDiv.textContent = err;
        } else {
            statusDiv.textContent = '上传成功';
            loadRecentFileList();
            loadFileList();
        }
    },
});

window.addEventListener('DOMContentLoaded', function () {
    switchTab('recent');
    loadRecentFileList();
    // 初始加载文件列表
    loadFileList();
});